package com.example.mongodb.dao.impl;

import com.example.mongodb.dao.StudentDao;
import com.example.mongodb.entity.Student;
import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StudentDaoImpl implements StudentDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addData(Student student) {
        mongoTemplate.insert(student);
        System.out.println(1/0);
        mongoTemplate.insert(student);
    }

    @Override
    public void delData(Long id) {
        Criteria criteria = Criteria.where("_id").is(id);
        Query query = Query.query(criteria);
        DeleteResult remove = mongoTemplate.remove(query,Student.class);
        System.out.println(remove);
    }

    @Override
    public Student getById(Object id) {
        List<Student> uid = mongoTemplate.find(Query.query(Criteria.where("uid").is("-8218903639601002431")), Student.class);
        for (Student student : uid) {
            System.out.println(student);
        }
        return mongoTemplate.findById(id, Student.class);
    }

    @Override
    public List<Student> getAll() {
        Query query = Query.query(new Criteria());
        List<Student> all = mongoTemplate.find(query,Student.class);
        return all;
    }
}
